﻿using LeonardoNews.Models;
using LeonardoNews.Server.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;

namespace LeonardoNews.Server.Repositories
{
    public class CommentsRepository
    {
        public CommentsRepository()
            : this(new LeonardoNews.Data.NewsContext())
        {
        }

        public CommentsRepository(DbContext context)
        {
            if (context == null)
            {
                throw new ArgumentException("An instance of DbContext is required to use this repository.", "context");
            }

            this.Context = context;
            this.DbSet = this.Context.Set<Comment>();
        }

        protected IDbSet<Comment> DbSet { get; set; }

        protected DbContext Context { get; set; }

        public IQueryable<Comment> All()
        {
            return this.DbSet.Include(c => c.User).Include(c => c.Article);
        }

        public Comment Get(int id)
        {
            return this.DbSet.Include(c => c.User).Include(c => c.Article).FirstOrDefault(c => c.ID == id);
        }

        public void Add(Comment item)
        {
            DbEntityEntry entry = this.Context.Entry(item);
            if (entry.State != EntityState.Detached)
            {
                entry.State = EntityState.Added;
            }
            else
            {
                this.DbSet.Add(item);
            }

            this.Context.SaveChanges();
        }

        public virtual void Delete(Comment entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);
            if (entry.State != EntityState.Deleted)
            {
                entry.State = EntityState.Deleted;
            }
            else
            {
                this.DbSet.Attach(entity);
                this.DbSet.Remove(entity);
            }

            this.Context.SaveChanges();
        }

        public void Delete(int id)
        {
            var entity = this.Get(id);

            if (entity != null)
            {
                this.Delete(entity);
            }
        }

        public void Update(int id, Comment item)
        {
            DbEntityEntry entry = this.Context.Entry(item);
            if (entry.State == EntityState.Detached)
            {
                this.DbSet.Attach(item);
            }

            entry.State = EntityState.Modified;

            this.Context.SaveChanges();
        }
    }
}